#!/bin/sh

. "$SPEC_PATH/abstract/dbops-restart"

e2e_test_extra_hash() {
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
    "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_PATH/abstract/dbops-restart")"
}

e2e_test() {
  run_test "Checking that restart is working" check_restart_is_working

  run_test "Checking that restart in-place is working" check_restart_in_place_is_working
  
  run_test "Checking that restart with only pendingin restart is working" check_restart_only_pending_restart_is_working
}

check_restart_is_working() {
  reset_cluster 1
  trigger_cluster_require_restart

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: restart
  restart:
    method: InPlace
EOF

  wait_until eval '[ "$(kubectl get sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME" \
    --template "{{ .status.opRetries }}")" = "0" ]'
  kubectl get sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME" -o yaml > "$LOG_PATH/sgdbops.yaml"
  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
  kubectl create -f "$LOG_PATH/sgdbops.yaml"

  check_restart

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
  set_restarted_pods "$CLUSTER_NAME-1"
  trigger_cluster_require_restart

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: restart
  restart:
    method: ReducedImpact
EOF

  check_restart

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
}

check_restart_in_place_is_working() {
  reset_cluster
  trigger_cluster_require_restart

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: restart
  restart:
    method: InPlace
EOF

  check_restart

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
}

check_restart_only_pending_restart_is_working() {
  reset_cluster

  kubectl patch sgcluster -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME" --type json \
    -p '[{"op":"add","path":"/spec/pods/disableConnectionPooling","value":true}]'
  wait_until eval "kubectl get sts -n '$CLUSTER_NAMESPACE' '$CLUSTER_NAME' -o template='{{range .spec.template.spec.containers}}.{{end}}' | grep -qxF ...."

  kubectl delete pod -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME-1"
  wait_pods_running "$CLUSTER_NAMESPACE" 3
  set_restarted_pods "$CLUSTER_NAME-0" "$CLUSTER_NAME-1"

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: restart
  restart:
    method: InPlace
    onlyPendingRestart: true
EOF

  check_restart

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
}

